//
//  LTHeadLine.m
//  wangyiNews08
//
//  Created by 123 on 16/3/11.
//  Copyright © 2016年 Tsr. All rights reserved.
//

#import "LTHeadLine.h"
#import <objc/runtime.h>
#import "LTNetwrokTool.h"

@implementation LTHeadLine

+ (instancetype)HeadLineWithDict:(NSDictionary *)dict {
    id obj = [[self alloc] init];
    
    NSArray *pros = [self properties];
    for (NSString *key in pros) {
        if (dict[key]) {
            [obj setValue:dict[key] forKey:key];
        }
    }
    
    return obj;
}

+ (void)headLineWithSuccess:(void (^)(NSArray *))success error:(void (^)(NSError *))error {
    
    [[LTNetwrokTool shareNetwrokTool] GET:@"ad/headline/0-4.html" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
        // 获得第一个key
        NSString *rootKey = responseObject.keyEnumerator.nextObject;
        
        NSArray *headArray = responseObject[rootKey];
        
        NSMutableArray *headLines = [NSMutableArray array];
        
        [headArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            // 字典转模型
            LTHeadLine *headLine = [LTHeadLine HeadLineWithDict:obj];
            // 添加数组
            [headLines addObject:headLine];
        }];
        
        if (success) {
            success(headLines);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull er) {
        if (error) {
            error(er);
        }
    }];
}

/**
 *  返回当前类所有的属性
 */
+ (NSArray *)properties {
    NSMutableArray *pros = [NSMutableArray array];
    // 属性的个数
    unsigned int count = 0;
    // 获得属性数组
    objc_property_t *property = class_copyPropertyList([self class], &count);
    //    char *names = {"zhangsan","lis"};
    for (NSInteger index = 0; index < count; index ++) {
        // 根据index获得对应的属性
        objc_property_t p = property[index];
        // 获得属性的名字
        const char *cname = property_getName(p);
        // 转换OC字符串
        NSString *name = [[NSString alloc] initWithCString:cname encoding:NSUTF8StringEncoding];
        // 将属性添加到数组中
        [pros addObject:name];
    }
    return pros;
}

@end
